<template>
    <div>
      <el-row :gutter="20" style="margin: 0 10px;">
         <el-col :lg="8">
            <page-main title="" style="margin: 10px 0 10px 0;">
             <span>地图名称</span>
              <el-select class="strech" v-model="dataManager.current.mapName" placeholder="请选择" @change="handleMapChange">
                <el-option
                v-for="map in dataManager.mapList"
                :key="map.id"
                :label="map.name"
                :value="map.name">
                </el-option>
            </el-select>

             <el-collapse v-model="activeCollapse" accordion>
              <el-collapse-item title="当前地图有以下点：" name="1">
                <!-- radio 选择 -->
                <el-radio-group  v-model="dataManager.current.positionName" @change="handlePositionChange">
                  <el-radio v-for="(positionName) in dataManager.positionNameList" :label="positionName" :key="positionName">{{ positionName }}</el-radio>
                </el-radio-group>
              </el-collapse-item>
            </el-collapse>

          <el-divider >获取地图</el-divider>
          <el-button type="success" @click="createMap" :disabled="canvasManager.editStatus">获取扫描</el-button>
          <el-button-group v-if="scanStatus">
            <el-button type="danger"  @click="cancelScan">终止扫描</el-button>
            <el-button type="primary" @click="stopScanMap" >保存地图</el-button>
          </el-button-group>

          <!-- <el-divider >地图上传</el-divider>
          <map-upload></map-upload> -->

          <el-divider content-position="left" >设置起点-在地图上选择小车所在位置为起点</el-divider> 
          <el-button type="success" @click="addPosition" :disabled="canvasManager.editStatus">设置初始点</el-button>
          <el-button-group v-if="canvasManager.editStatus">
            <el-button type="success" @click="savePosition">开始初始化</el-button>
            <el-button type="danger" @click="cancel">取消</el-button>
          </el-button-group>
       
            </page-main>
          </el-col>
         <el-col :lg="16">
        <page-main title="地图" style="margin: 10px 0 10px 0;" id="mapcover">
            <div class="question">
              <canvas id="map" class="map"></canvas>
            </div>
        </page-main>

        <el-dialog title="提示" :visible.sync="progressBar.initDialogVisible" width="30%" :modal="true" :show-close="false" 
          :close-on-click-modal="false" :close-on-press-escape="false" center lock-scroll 
        >
        <div style="text-align: center;">
          <el-progress type="circle" :percentage="progressBar.percentage" :width="150" :status="progressBar.progressStatus"></el-progress>
          <div style="clear: both; margin-top: 10px;">{{this.webSocket.taskStatus.statusCode}}:{{this.webSocket.taskStatus.statusMsg}}</div>
          <div v-if="progressBar.percentage<100" style="clear: both;">小车正在转圈初始化，定位自己位置中</div>
          <div v-else-if="progressBar.percentage==100" style="clear: both;">初始化完成，检查小车位置是否正确</div>
        </div>
          <span slot="footer" class="dialog-footer">
            <el-button v-if="progressBar.percentage<100" type="danger" @click="closeDialog();stopInitialize()">中止初始化</el-button>
            <el-button v-else-if="progressBar.percentage==100" type="success" @click="closeDialog();">确认</el-button>
          </span>
        </el-dialog>
          </el-col>
         
          <el-col :lg="24">
          <page-main title="" style="margin: 0 0 20px 0;">
                    <el-table
                    ref="filterTable"
                    :data="tableData.slice((currentPage-1)*pageSize,currentPage*pageSize).filter(data => !search || data.name.toLowerCase().includes(search.toLowerCase()))" 
                    style="width: 100%;"
                    v-loading= 'loading'
                    >
                    <el-table-column type="index"></el-table-column>   

                    <el-table-column
                      prop="name"
                      label="地图名(户号)"
                      sortable         
                      column-key="name">
                    </el-table-column>

                     <el-table-column
                      prop="createdAt"
                      label="创建时间"
                      sortable         
                      column-key="createdAt">
                    </el-table-column>

                    <el-table-column
                    width="200px"
                     >   
                    <template slot="header" slot-scope="scope">
                    <el-input
                      v-model="search"
                      size="mini"
                      placeholder="输入地图名"/>
                    </template>  
                    <template slot-scope="scope">                           

                    <el-dropdown>
                    <el-button icon="el-icon-menu" circle size="mini"></el-button>
                    <el-dropdown-menu  slot="dropdown">
                 
                      <el-dropdown-item >
                      <el-button type="primary" size="mini"  @click="downloadMap(scope.row)">下载当前地图</el-button>
                      </el-dropdown-item >

                      <el-dropdown-item >
                      <el-button type="primary" size="mini" @click="renameMap(scope.row)" >修改地图名称</el-button>
                      </el-dropdown-item >

                      </el-dropdown-menu>
                      </el-dropdown>
                     <el-button style="margin-left: 10px;" type="danger" icon="el-icon-delete" size="mini"  @click="deleteMap( scope.row)" circle></el-button>
                               
                    </template>
                    </el-table-column>                
                </el-table>
                <div class="block" style="margin-top: 15px;">
                    <el-pagination align='center' @size-change="handleSizeChange" @current-change="handleCurrentChange" 
                    :current-page="currentPage" 
                    :page-sizes="[1,5,10,20]" 
                    :page-size="pageSize" 
                    layout="total, sizes, prev, pager, next, jumper" 
                    :total="tableData.length">
                    </el-pagination>
                </div>

          </page-main>
        </el-col>
    
  </el-row>
 </div>
</template>

<script>
import CanvasManager from '@/static/CanvasManagerPosition'
import DataManager from '@/static/DataManagerPosition'
import gsApi from "@/api/gsApi"
import WebSocket from '@/static/WebSocket.js'
import ProgressBar from '@/static/ProgressBar'
import { setTimeout } from 'tinymce/themes/silver/theme'

  export default {
    name: "test",
    data() {
      return {
        tableData: [],
        currentPage: 1, // 当前页码
        total: 20, // 总条数
        pageSize: 10, // 每页的数据条数
        search: '',
        loading:false,
        canvasManager:'',
        dataManager:new DataManager(),
        webSocket:new WebSocket(),
        activeCollapse:'1',
        scanStatus:false,
        progressBar:new ProgressBar(),
      }
    },
    created(){
    },
    mounted() {
      this.loadData();
      this.getTabelInfo()
      this.webSocket.startWebSocket()
      this.preventScroll()
    },
    methods:{
      async loadData(){
        await this.dataManager.loadMaps();
        await this.dataManager.location();
        await this.dataManager.loadPositions(this.dataManager.mapList[0].name);
       
        // 这里需要等待数据加载完后，再初始化canvasManager。因为需要知道第一张地图的名字，用作显示
        this.canvasManager=new CanvasManager({
          canvasId:'map',
          mapName:this.dataManager.mapList[0].name,
        })
      },

      async getTabelInfo(){
            const res = await gsApi.getMapList()
            this.loading = false
            this.tableData = res.data.data
      },

      handleMapChange(mapName){
        this.canvasManager.reloadImg(mapName);
        this.dataManager.loadPositions(mapName);
      },

      handlePositionChange(positionName){
        // 1. 清除画布的圆和字
        this.canvasManager.clearObjectCircle();
        this.canvasManager.clearObjectText();
        // 2. 再绘制新的点
        this.canvasManager.drawPosition({positionName,dataManager:this.dataManager});
      },

       handleSizeChange(val) {
          this.currentPage = 1;
          this.pageSize = val;
      },
      //当前页改变时触发 跳转其他页
      handleCurrentChange(val) {
          this.currentPage = val;
      },

      addPosition(){//添加定点
        // this.canvasManager.clearObject(); // 清理地图路径
          this.canvasManager.clearObjectCircle();
          this.canvasManager.clearObjectText();
          this.canvasManager.editStatus=true;
          this.canvasManager.clickStatus=true;
      },

      cancel(){
          // 清理canvas 暂存的打点数据
          this.canvasManager.clearObjectCircle();
          this.canvasManager.clearObjectText();
          this.canvasManager.tempPoints=[];
          // 退出编辑状态
          this.canvasManager.clickStatus=false;
          this.canvasManager.editStatus=false;
          //清空tempPosition信息，以免点保存的时候误保存最后一次遗留的点
          this.canvasManager.tempPosition={};
      },

     /**
       * 保存定点数据
       */
      async savePosition(){
            // 根据再canvas上 打的点，生成要提交的数据
            let positionBean=this.canvasManager.generatePosition();
          if(positionBean.name==undefined){
            this.$message.info("请先在图片上打点")
            return 
          }
            this.progressBar.initDialogVisible = true
            positionBean.name = Date.parse(new Date())
          try{
            const res = await gsApi.insertPosition(positionBean);
            if(res.data.msg==='successed'){
            this.$message.success('选择成功，开始初始化')
            await this.initialize(this.dataManager.current.mapName,positionBean.name)
            await gsApi.deletePosition(this.dataManager.current.mapName,positionBean.name)
            this.cancel()
            }else{
            this.$message.error("出现问题" + res.data.msg)
            }
          }
          catch(err){
            console.log(err)
            this.$message.error("出现异常，详见控制台")
          }
      },
      
      async initialize(mapName,positionName){
         this.progressBar.percentageShow(15,this.webSocket)
         if(positionName == null){
           this.$message.info('当前位置为空')
           return
         }
         try {
           const res = await gsApi.initialize(mapName,positionName);
           if(res.data.msg==='successed'){
             this.$message.success('初始化启动')
           }else{
            this.$message.error(res.data.msg);
           }
         }catch (err) {
           console.log(err);
           this.$message.error('网络异常')
         }
      },

      async scanMap(value){//新建扫描
        try {
            const res = await gsApi.scanMap(value)
            if(res.data.msg === 'successed'){
              this.$message.success('新建成功,开始扫描')
            }else{
              this.$message.error(res.data.msg);
            }
            }catch (err) {
              console.log(err);
              this.$message.error('网络异常')
            }
      },

      createMap(){//新建扫描
        this.$prompt('请输入地图名称', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
        }).then(({ value }) => {
          this.scanStatus=true
          //启动扫描模块
          this.scanMap(value);
          //启动地图实时刷新模块
          this.canvasManager.clearMap();
          setTimeout(() => {
            this.scanIntervalFlag = setInterval(() => {
              this.canvasManager.loadScanningImg();
            }, 500);
          }, 7000);  //7000代表7秒后开始获取地图，等待扫描模块启动的时间
        }).catch((err) => {
          console.log(err)    
        });
      },

      async cancelScan(){//终止扫描
        try {
          const res = await gsApi.cancelScan()
          clearInterval(this.scanIntervalFlag);
          if(res.data.msg==='successed'){
            this.scanStatus=false;
            this.$message.success('扫描已取消')
          }else{
            this.$message.error(res.data.msg);
          }
        }catch (err) {
          console.log(err);
          this.$message.error('网络异常')
        }
      },
      async stopScanMap(){//结束扫描保存地图(异步)
      try {
        const res = await gsApi.stopScanMap()
        if(res.data.msg==='successed'){
          this.$message.success('扫描成功');
          //试过加await 但是没用
          await this.loadData()
          await this.getTabelInfo()
          }else{
            this.$message.error(res.data.msg);
            }
        }catch (err) {
          console.log(err);
          this.$message.error('网络异常')
        }
      },

        renameMap(row){//修改名称
        this.$prompt('请输入地图新名称', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
        }).then(async({ value }) => {
          try {
              const res = await gsApi.renameMap(row.name,value)
              if(res.data.msg==='successed'){
                this.$message.success('修改地图成功')
              }else{
                this.$message.error(res.data.msg);
              }
            }catch (err) {
              console.log(err);
              this.$message.error('网络异常')
            }
          this.loadData()
          this.getTabelInfo()
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消'
          });       
        });
      },

      deleteMap(row){//删除地图
      this.$confirm('此操作将永久删除该地图, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(async() => {
              try {
              const res = await gsApi.deleteMap(row.name)
              if(res.data.msg==='successed'){
                this.$message.success('删除该地图成功')
              }else{
                this.$message.error(res.data.msg);
              }
            }catch (err) {
              console.log(err);
              this.$message.error('网络异常')
            }
            this.loadData()
            this.getTabelInfo()
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });          
        });
      },

      downloadMap(row){//下载地图
        try {
          location.href="gs-robot/data/download_map?map_name="+row.name;
          this.$message.success('下载该地图成功')
          // window.open(res);
        }catch (err) {
          console.log(err);
          this.$message.error('网络异常')
        }
      },
       
      async stopInitialize(){
        const res = gsApi.stopInitialize()
      },
      
      closeDialog(){
          clearInterval(this.progressBar.IntervalFlag)
          this.progressBar.percentage = 0
          this.progressBar.initDialogVisible=false;
          this.progressBar.progressStatus = null;
      },
      preventScroll(){
        let mapcover = document.getElementById("mapcover");
        console.log('执行了')
        mapcover.onmouseout = ()=>{
          document.documentElement.style.overflow='auto';
        }
        mapcover.onmouseover = ()=>{
          document.documentElement.style.overflow='hidden';
        }
      }
    }
  }

</script>

